package com.zoe.onelink.core.async;

import com.zoe.onelink.util.OnelinkContextHolder;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>标题: 多线程上下文复制</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-07-26
 */
public class OnelinkContextTaskDecorator implements TaskDecorator {

    private static final OnelinkContextTaskDecorator DECORATOR = new OnelinkContextTaskDecorator();

    /**
     * 这里不能设置private,涉及太多旧项目依赖改造问题
     */
    public OnelinkContextTaskDecorator() {

    }

    public static OnelinkContextTaskDecorator getInstance() {
        return DECORATOR;
    }

    @Override
    public Runnable decorate(Runnable runnable) {
        final long parentThreadId = Thread.currentThread().getId();
        final Map<String, Object> onelinkContextCopiedMap = new HashMap<>(OnelinkContextHolder.getCopiedMap());
        final Map<String, String> mdcContextCopiedMap = MDC.getCopyOfContextMap();
        return () -> {
            long childThreadId = Thread.currentThread().getId();
            boolean isDiffThread = parentThreadId != childThreadId;
            if (isDiffThread) {
                OnelinkContextHolder.putValue(onelinkContextCopiedMap);
                if (mdcContextCopiedMap != null) {
                    MDC.setContextMap(mdcContextCopiedMap);
                }
            }
            try {
                runnable.run();
            } finally {
                if (isDiffThread) {
                    OnelinkContextHolder.clear();
                    MDC.clear();
                }
            }
        };
    }

}
